//
//  RHMQTTTestController.m
//  RuiHeAppApp
//
//  Created by Jun on 2023/8/11.
//

#import "RHMQTTTestController.h"
#import "RHMqttDevRegionListController.h"
#import "RHDevRegionModel.h"
#import "QMUILabel+LHAdd.h"
#import "RHMQTTServerInfoModel.h"
#import "RHMqttFuncListController.h"
#import "RHMQTTManage.h"
#import "RHMQDevModel.h"
#import "NetworkConfig.h"
#import "RHDeviceModel.h"
#import "ChoiceDeviceVC.h"
#import "EnvironmentManage.h"


@interface RHMQTTTestController ()

@property (nonatomic ,strong) RHDevRegionModel *regionModel;

@property (nonatomic ,strong) RHMQTTServerInfoModel *infoModel;

@property (nonatomic ,strong) QMUILabel *titleLab;

@property (nonatomic ,strong) QMUILabel *codeLab;

@property (nonatomic ,strong) QMUILabel *contentLab;

@property (nonatomic ,strong) UITextField *deviceTF;

@property (nonatomic ,strong) UITextField *secretTF;

@property (nonatomic ,strong) RHDeviceModel *curDevModel;
@end

@implementation RHMQTTTestController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear: animated];
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"MQTT模拟测试"];
    [self.view setBackgroundColor:CFTabViewBgColor];
    [self setupUI];
}


- (void)setRegionModel:(RHDevRegionModel *)regionModel{
    _regionModel = regionModel;
    [_titleLab setText:_regionModel.countryName];
    [_codeLab setText:_regionModel.countryCode];
    
    [self getServerInfoFromNetwork];
}


- (void)setInfoModel:(RHMQTTServerInfoModel *)infoModel{
    _infoModel = infoModel;
    [_contentLab setTextColor:kCOLOR_HEX(@"666666")];
    NSString *content = [NSString stringWithFormat:@"areaCode：%@\n\nareaName：%@\n\nmqttAddress：%@\n\napiAddress：%@\n\nmanageAddress：%@\n\ndefaultFalg：%@",_infoModel.areaCode,_infoModel.areaName,_infoModel.mqttAddress,_infoModel.apiAddress,SafeStr(_infoModel.manageAddress),_infoModel.defaultFalg];
    [_contentLab setText:content];
    CGSize size = [_contentLab getLableSizeWithMaxWidth:SCREEN_WIDTH-30];
    [_contentLab mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(size.height);
    }];
}


- (void)setupUI{
    
    UIScrollView *scroll = [[UIScrollView alloc] init];
    [self.view addSubview:scroll];
    scroll.backgroundColor = [UIColor clearColor];
    
    UIView *contentView = [[UIView alloc] init];
    contentView.backgroundColor = [UIColor clearColor];
    [scroll addSubview:contentView];
    
    QMUILabel *devTapLab = [[QMUILabel alloc] init];
    [devTapLab setTextAlignment:NSTextAlignmentLeft];
    [devTapLab setFont:[UIFont systemFontOfSize:13]];
    [devTapLab setTextColor:kCOLOR_HEX(@"666666")];
    [devTapLab setText:@"设备ID"];
    [contentView addSubview:devTapLab];
    
    UIView *devView = [[UIView alloc] init];
    [devView setBackgroundColor:UIColor.whiteColor];
    [contentView addSubview:devView];
    
    UITextField *devTextField = [[UITextField alloc] init];
    [devTextField setPlaceholder:@"请选择设备"];
    [devTextField setFont:[UIFont systemFontOfSize:15]];
    [devTextField setTextColor:kCOLOR_HEX(@"666666")];
    [devView addSubview:devTextField];
    devTextField.userInteractionEnabled = NO;
    _deviceTF = devTextField;
    
    
    QMUIButton *selectBtn = [[QMUIButton alloc]init];
    [selectBtn setImage:[UIImage imageNamed:@"arrow_down"] forState:UIControlStateNormal];
    selectBtn.imagePosition = QMUIButtonImagePositionRight;
    selectBtn.spacingBetweenImageAndTitle = kUI_WINDOW_W - 40 -30;
    [selectBtn setTitle:@" " forState:UIControlStateNormal];
    [devView addSubview:selectBtn];
    [selectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    kWeakSelf;
    [[selectBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf deviceList];
    }];
    
    QMUILabel *secretTapLab = [[QMUILabel alloc] init];
    [secretTapLab setTextAlignment:NSTextAlignmentLeft];
    [secretTapLab setFont:[UIFont systemFontOfSize:13]];
    [secretTapLab setTextColor:kCOLOR_HEX(@"666666")];
    [secretTapLab setText:@"设备密钥"];
    [contentView addSubview:secretTapLab];
    
    UIView *secretView = [[UIView alloc] init];
    [secretView setBackgroundColor:UIColor.whiteColor];
    [contentView addSubview:secretView];
    
    UITextField *secretTextField = [[UITextField alloc] init];
    [secretTextField setPlaceholder:@"请输入设备密钥"];
    [secretTextField setFont:[UIFont systemFontOfSize:15]];
    [secretTextField setTextColor:kCOLOR_HEX(@"666666")];
    [secretView addSubview:secretTextField];
    _secretTF = secretTextField;
    
    QMUILabel *tapLab = [[QMUILabel alloc] init];
    [tapLab setTextAlignment:NSTextAlignmentLeft];
    [tapLab setFont:[UIFont systemFontOfSize:13]];
    [tapLab setTextColor:kCOLOR_HEX(@"666666")];
    [tapLab setText:@"设备所在区域"];
    [contentView addSubview:tapLab];
    
    UIView *view = [[UIView alloc] init];
    [view setBackgroundColor:UIColor.whiteColor];
    [contentView addSubview:view];
    
    _titleLab = [[QMUILabel alloc] init];
    [_titleLab setTextAlignment:NSTextAlignmentLeft];
    [_titleLab setFont:[UIFont systemFontOfSize:15]];
    [_titleLab setTextColor:kCOLOR_HEX(@"999999")];
    [_titleLab setText:@"请选择区域"];
    [view addSubview:_titleLab];
    
    _codeLab = [[QMUILabel alloc] init];
    [_codeLab setTextAlignment:NSTextAlignmentRight];
    [_codeLab setFont:[UIFont systemFontOfSize:15]];
    [_codeLab setTextColor:kCOLOR_HEX(@"666666")];
    [_codeLab setText:@""];
    [view addSubview:_codeLab];
    
    
    UIImageView *arrowV = [[UIImageView alloc] init];
    [arrowV setImage:[UIImage imageNamed:@"arrow"]];
    [view addSubview:arrowV];
    
    UITapGestureRecognizer *tapView = [[UITapGestureRecognizer alloc] init];
    view.userInteractionEnabled = YES;
    [view addGestureRecognizer:tapView];
    
    
    QMUILabel *tapLab2 = [[QMUILabel alloc] init];
    [tapLab2 setTextAlignment:NSTextAlignmentLeft];
    [tapLab2 setFont:[UIFont systemFontOfSize:13]];
    [tapLab2 setTextColor:kCOLOR_HEX(@"666666")];
    [tapLab2 setText:@"服务器信息"];
    [contentView addSubview:tapLab2];
    
    UIView *view2 = [[UIView alloc] init];
    [view2 setBackgroundColor:UIColor.whiteColor];
    [contentView addSubview:view2];
    
    _contentLab = [[QMUILabel alloc] init];
    [_contentLab setTextAlignment:NSTextAlignmentLeft];
    [_contentLab setFont:[UIFont systemFontOfSize:15]];
    [_contentLab setTextColor:kCOLOR_HEX(@"999999")];
    [_contentLab setText:@"暂无服务信息\n请先选择设备所在区域"];
    [_contentLab setNumberOfLines:-1];
    [view2 addSubview:_contentLab];
    
    QMUILabel *evenLab = [[QMUILabel alloc] init];
    [evenLab setTextAlignment:NSTextAlignmentLeft];
    [evenLab setFont:[UIFont systemFontOfSize:13]];
    [evenLab setTextColor:kCOLOR_HEX(@"666666")];
    [evenLab setText:@"当前环境"];
    [contentView addSubview:evenLab];
    
    UIView *view3 = [[UIView alloc] init];
    [view3 setBackgroundColor:UIColor.whiteColor];
    [contentView addSubview:view3];
    
    QMUILabel* evenContentLab = [[QMUILabel alloc] init];
    [evenContentLab setTextAlignment:NSTextAlignmentLeft];
    [evenContentLab setFont:[UIFont systemFontOfSize:15]];
    [evenContentLab setTextColor:kCOLOR_HEX(@"999999")];
    [evenContentLab setText:[EnvironmentManage sharedEnvirManage].getCurrentEnvironment];
    [evenContentLab setNumberOfLines:-1];
    [view3 addSubview:evenContentLab];
    
    
    QMUIButton *switchBtn = [[QMUIButton alloc]init];
    [switchBtn setBackgroundColor:CFMainColor];
    [switchBtn setCornerRadius:8];
    [switchBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [switchBtn setTitle:@"切换本地服务器" forState:UIControlStateNormal];
    [self.view addSubview:switchBtn];
    

    QMUIButton *connectBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [connectBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [connectBtn setBackgroundColor:CFMainColor];
    [connectBtn.layer setCornerRadius:8];
    [connectBtn setTitle:@"开始连接" forState:UIControlStateNormal];
    [connectBtn.titleLabel setFont:[UIFont boldSystemFontOfSize:15]];
    [contentView addSubview:connectBtn];

  
    [scroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(weakSelf.view);
    }];
    
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(scroll);
        make.width.mas_equalTo(scroll);
        make.height.greaterThanOrEqualTo(@0.f);//此处保证容器View高度的动态变化 大于等于0.f的高度
    }];

    [devTapLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.top.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(20);
    }];
    
    [devView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(devTapLab.mas_bottom).offset(5);
        make.height.mas_equalTo(50);
    }];
    
    [devTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(5, 15, 5, 15));
    }];
    
    [secretTapLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.top.equalTo(devView.mas_bottom).offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(20);
    }];
    
    [secretView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(secretTapLab.mas_bottom).offset(5);
        make.height.mas_equalTo(50);
    }];
    
    [secretTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(5, 15, 5, 15));
    }];
    
    [tapLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.top.equalTo(secretView.mas_bottom).offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(20);
    }];
    
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(tapLab.mas_bottom).offset(5);
        make.height.mas_equalTo(50);
    }];
    
    [tapLab2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.top.equalTo(view.mas_bottom).offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(20);
    }];
    
    [view2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(tapLab2.mas_bottom).offset(5);
    }];
    
    
    [evenLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.top.equalTo(view2.mas_bottom).offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(20);
    }];
    
    [view3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(evenLab.mas_bottom).offset(5);
    }];
    
    [evenContentLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(15, 15, 15, 15));
    }];
    
    [_contentLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.mas_offset(15);
        make.height.mas_equalTo(40);
        make.bottom.mas_offset(-15);
    }];
    
    [_titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_offset(0);
        make.left.mas_offset(15);
        make.width.mas_equalTo(100);
    }];
    
    [_codeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.titleLab.mas_right);
        make.top.bottom.equalTo(weakSelf.titleLab);
        make.right.equalTo(arrowV.mas_left).offset(-5);
    }];
    
    [arrowV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(20, 20));
        make.right.mas_offset(-15);
        make.centerY.mas_offset(0);
    }];
    
    [switchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.right.mas_offset(-15);
            make.height.mas_offset(50);
            make.top.equalTo(view3.mas_bottom).mas_offset(50);
    }];
    
    
    [connectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(switchBtn.mas_bottom).offset(30);
        make.bottom.mas_offset(-kBottomToolBar-50);
        make.height.mas_equalTo(50);
    }];
    
#pragma mark ------ 切换本地服务器 ------
    [[switchBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [NetworkConfig sharedConfig].baseUrl = @"http://192.168.100.59:9090/dev-api/";
        [QMUITips showSucceed:@"已切换"];
    }];
    
    
    [tapView.rac_gestureSignal subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
        [weakSelf selectRegion];
    }];
    
    [[connectBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf connectMqttServer];
    }];
    
//    [self.deviceTF setText:@"RZ18SLRPSWRN23160107"];
//    [self.deviceTF setText:@"AC1001011001"];
    [self.secretTF setText:@"123456"];
}

//选择设备
-(void)deviceList
{
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"userId":@([PrivateMange share].currentUser.userId),
                           @"pageNum":@(1),
                           @"pageSize":@(10000),
                           @"status":@""
    };
    [RHDeviceModel startGetWithCompletionAPIKey:H_deviceList argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            
            NSMutableArray *arr = [NSMutableArray arrayWithArray:resultModel.data];
            ChoiceDeviceVC *vc = [[ChoiceDeviceVC alloc]init];
            vc.deviceList = arr;
            vc.curModel = self.curDevModel;
            [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
            [vc showAnimation];
            kWeakSelf;
            vc.choiceResultBlock = ^(RHDeviceModel * _Nonnull model) {
                if(model){
                    weakSelf.curDevModel = model;
                    weakSelf.deviceTF.text = model.deviceId;
                }
            };
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
         
    }];
    
    
    
}

//选择区域
- (void)selectRegion{
    RHMqttDevRegionListController *vc = [[RHMqttDevRegionListController alloc] initWithModel:self.regionModel];
    [self.navigationController pushViewController:vc animated:YES];
    
    kWeakSelf;
    vc.callBackModel = ^(RHDevRegionModel * _Nonnull model) {
       
        weakSelf.regionModel = model;
    };
}

//获取服务信息
- (void)getServerInfoFromNetwork{
  
    NSDictionary *para = @{@"countryCode":self.regionModel.countryCode,
                           @"brandId":[NetworkConfig sharedConfig].brandID,
                           @"requestType":@(1)
                          };
    [RHMQTTServerInfoModel startWithBaseUrl:[EnvironmentManage sharedEnvirManage].getBaseAPIUrl APIKey:G_getServerInfo argument:para requestMethod:RequestMethodPOST requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.data){
            self.infoModel = resultModel.data;
            [NetworkConfig sharedConfig].baseUrl = self.infoModel.apiAddress;
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

#pragma mark ------ 连接 mqtt 服务器
//链接
- (void)connectMqttServer{
    
    if(self.deviceTF.text.length ==0){
        [QMUITips showWithText:@"请输入设备ID"];
        return;
    }
    
    if(self.secretTF.text.length == 0){
        [QMUITips showWithText:@"请输入设备密钥"];
        return;
    }
    
    if(!self.regionModel){
        [QMUITips showWithText:@"请选择设备所在区域"];
        return;
    }
    
    RHMqttFuncListController *vc = [[RHMqttFuncListController alloc] init];
    NSArray *arr = [self.infoModel.mqttAddress componentsSeparatedByString:@":"];
    NSString *host = @"";
    if(arr.count>=2){
        host = [NSString stringWithFormat:@"%@",[arr[1] stringByReplacingOccurrencesOfString:@"//" withString:@""]];
    }
  
    uint32_t port = [[arr lastObject] unsignedIntValue];

    
    //[NSString stringWithFormat:@"mqtt://%@",host]
    [[RHMQTTManage shareMQTTManage] setMqtt_host:host];
    [[RHMQTTManage shareMQTTManage] setMqtt_port:port];
//    [[RHMQTTManage shareMQTTManage] setMqtt_host:@"47.106.152.37"];
//    [[RHMQTTManage shareMQTTManage] setMqtt_port:1883];

    RHMQDevModel *model = [[RHMQDevModel alloc] init];
    model.devId = self.deviceTF.text;
    model.secretKey = self.secretTF.text;
    model.deviceTypeCode = self.curDevModel.deviceTypeCode;
    [[RHMQTTManage shareMQTTManage] setDevModel:model];

    [QMUITips showLoadingInView:self.view];
    kWeakSelf;
    [[RHMQTTManage shareMQTTManage] connectMqtt:^(BOOL isSuccess) {
        [QMUITips hideAllTips];
        if(isSuccess){
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
    }];
    
    //[[RHMQTTManage shareMQTTManage] contentMqtt:@"root1" password:@"root22"];
    //[[RHMQTTManage shareMQTTManage] multipleContentMqtt:1 ueseName:@"root" password:@"root"];
    

}



@end
